<template>
  <div>
    <!--<el-scrollbar style="height:100%">-->
      <el-container>
        <el-header style="height: 150px">
           <ul class="write_head">
             <li>
               <!--封面图片-->
               <div  >
               <!--<el-image :src="src" fit="cover"  style="width: 100%; height: 100%;vertical-align: middle">-->
               <!--<div slot="placeholder" class="image-slot">-->
               <!--加载中<span class="dot">...</span>-->
               <!--</div>-->
               <!--</el-image>-->
                 <el-upload

                   class="avatar-uploader"
                   action="http://49.235.21.244/blog/blog/uploadIndexImg"
                   :show-file-list="false"
                   :on-success="handleAvatarSuccess"
                   :before-upload="beforeAvatarUpload">
                   <img style="border: 1px dashed red" v-if="imageUrl" :src="imageUrl" class="avatar" alt="设置封面">
                   <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                 </el-upload>
               </div>
             </li>
             <li>
               <el-input
                 style="margin-top: 10px;font-size: 18px;line-height: 1"
                 type="textarea"
                 :rows="2"
                 placeholder="文章的简单描述"
                 v-model="description">
               </el-input>

               <el-form :inline="true"  class="demo-form-inline">
                 <el-form-item class="head_select">
                   <el-select v-model="label" placeholder="选择标签">
                     <el-option :label="item.value" :value="item.id" v-for="(item,index) in $store.state.labelList" :key="index"></el-option>

                   </el-select>
                 </el-form-item>
                 <el-col :span="18" style="float: right">
                 <el-form-item class="head_title">
                     <el-input  id="title" v-model="title" placeholder="请输入文章标题" maxlength="50" show-word-limit></el-input>
                 </el-form-item>
                 </el-col>
               </el-form>
             </li>
             <li>

                 <el-button class="head_btn"  type="primary" @click="submitArticle" icon="el-icon-check">保存</el-button>

                 <el-button class="head_btn"   type="primary" icon="el-icon-delete" @click="goback()">返回</el-button>

             </li>

           </ul>



          <!--<div style="margin-top: 15px;">-->

          <!--</div>-->

          <!--标题-->

        </el-header>


        <el-main class="time_line">
          <vueToTop type="4" size="50" color="#b640ff" bottom="100"></vueToTop>
          <el-divider><span>当前时间:{{nowTime}}</span></el-divider>
           <!--markdown 编辑器-->
          <div id="main">
            <mavon-editor placeholder="There is no doubt that I  love Java forever" :ishljs = "true" v-model="content"
                         style="min-height: 600px" @imgAdd="$imgAdd" ref="md"
            />
          </div>
        </el-main>


      </el-container>

  <!--</el-scrollbar>-->
  </div>

</template>

<script>
   import  commonUtils  from  '../common/commonUtils'
  export default {
    name: 'writeArticle',
    data(){
      return {
        imageUrl: '',
        content: '',
        label: '',   //文章的标签id
        title: '',
        src: 'https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg',
        nowTime: '',
        description: '' //文件的描述。
      }
    },
    mounted () {
      // commonUtils.AlertLoading("","iconfont icon-jiazai1")
     this.flushTime()
      this.initData();
      this.intitEditor();
    },
    methods:{
      //初始化富文本编辑器的内容,
      intitEditor(){
        console.log("本次的参数id==>"+this.$route.params.id)
        if (this.$route.params.id == 0) {
           return;
        }else {
          this.axios.post("/blog/getArticle?id="+this.$route.params.id).then(success =>{
            if (success.data.code == 0) {
              var dto = success.data.result
              this.label= dto.content.labelId;
              this.imageUrl =dto.content.indexImg
              this.title =dto.content.title
              this.content =dto.content.content
              this.description =dto.content.description;
            }else if (success.data.code == -2) {
               commonUtils.AlertOperationSuccess(success.data.result,1000)
            }else {
              commonUtils.AlertErrorMsg("获取文章内容失败!")
            }
          }).catch(error =>{
            commonUtils.AlertErrorMsg("获取文章内容失败,请检查!")
          })
        }

      },

      goback(){
         this.$router.replace("/blog")
      },
      //上传。。。。文章
      submitArticle(){
        if (!this.content) {
            commonUtils.AlertOperationSuccess("先写点什么把！",1000)
            return;
        }
        if (!this.label) {
            commonUtils.AlertOperationSuccess("请选择标签!",1000)
            return
        }
        if (!this.title) {
          commonUtils.AlertOperationSuccess("请输入标题!",1000)
           return;
        }
        var  params={
           contentId:this.$route.params.id,
           imgUrl:this.imageUrl,
           label: this.label,
           title: this.title,
           content: this.content,
          description:this.description
        }
        console.log(params)
        this.axios.post("/write/writeBlog",params).then(success =>{
          if (success.data.code == 0) {
              commonUtils.AlertOperationSuccess("发布成功!",1000)

          }else {
             if(success.data.code ==-2){
               commonUtils.AlertOperationSuccess(success.data.result,1000)
               return
             }
             if (success.data.code ==-1) {
               commonUtils.AlertOperationSuccess("提交失败,请联系管理员!",1000)
               return
             }
          }

        }).catch(error =>{
             commonUtils.AlertErrorMsg("提交失败,请联系管理员!")

        })

      },
      //图片上传成功的回调
      handleAvatarSuccess(res, file) {
        console.log(res)
        if (res.code == 0) {
          // this.imageUrl = URL.createObjectURL(file.raw);
          this.imageUrl=res.result;
          console.log(this.imageUrl)
          commonUtils.AlertOperationSuccess('上传成功！', 1000)
        }
        if (res.code == -2) {
            commonUtils.AlertErrorMsg(res.result)
          return;
        }
        if (res.code == -1) {
          commonUtils.AlertErrorMsg("上传失败!")
        }
      },
      //图片上传前的回调。
      beforeAvatarUpload(file){
        var nameArr= ["png","jpg","jpeg"]
        var fileName = file.name;
        console.log(fileName)
        var isLt2M = file.size / 1024 / 1024 < 2;
        var index = fileName.lastIndexOf('.')
          var substring = fileName.substring(index+1)
        console.log(substring)
        var isJPG=  nameArr.some( item =>{
          return item === substring.toLowerCase()
          })
        console.log("isJPG==>"+isJPG)
        if (!isJPG) {
          this.$message.error('上传图片只能是 jpg/png 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },

      //实时显示时间
      flushTime(){
         var _this=this;
          setInterval( ()=> {
            var now = new Date()
            var year = now.getFullYear()
            var month = now.getMonth()
            var date = now.getDate()
            var text=year+"年"+month+"月"+date+"日 "+now.toLocaleTimeString();
            _this.nowTime = text
          },1000);

      },
      //初始化下拉框
      initData(){
        if (!this.$store.state.labelList.length > 0) {
          this.$store.dispatch('initData')
        }
      },

      //富文本编辑器的图片上传
      $imgAdd(pos, $file){
        // 第一步.将图片上传到服务器.
        var formdata = new FormData();
        formdata.append('file', $file);
        this.axios({
          url: '/blog/uploadIndexImg',
          method: 'post',
          data: formdata,
          headers: { 'Content-Type': 'multipart/form-data' },
        }).then((success) => {
          // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
          // $vm.$img2Url 详情见本页末尾
          console.log(success.data.result)
          this.$refs.md.$img2Url(pos, success.data.result);
        })
      }
    },


  }
</script>

<style scoped>

  .el-header, .el-footer {
    background-color: #B3C0D1;
    color: #333;
    text-align: center;
    line-height: 60px;
  }

  .el-aside {
    background-color: #D3DCE6;
    color: #333;
    text-align: center;
    line-height: 200px;

  }

  .el-main {
    background-color: #E9EEF3;
    color: #333;
    text-align: center;
    line-height: 160px;
  }

  body > .el-container {
    margin-bottom: 40px;
  }

  .el-container:nth-child(5) .el-aside,
  .el-container:nth-child(6) .el-aside {
    line-height: 260px;
  }

  .el-container:nth-child(7) .el-aside {
    line-height: 320px;
  }

  /*--------自定义样式-------*/




  .el-header, .el-main{
    /*height: 300px; 不起作用 内联样式*/
    /*background-color: #92ff4b;*/
    margin-right: 5%;
    margin-left: 5%;
    margin-top: 10px;
  }
  .write_head li{
     list-style: none;
     float: left;
     /*margin-right: 1%;*/
    /*margin-left: 1%;*/
     height:150px;
  }
  .write_head li:nth-of-type(1){
    /*background-color: red;*/
    width: 16%;
    position: relative;
  }
  .write_head  .el-upload-dragger{
    height: 100%;
    width: 100%;
     position: absolute;
     left: 0;
    right: 0;
    bottom: 0;
    top: 0;
    margin: auto;
  }
  .el-upload__text{
      position: absolute;
     top: 0;
  }
  .el-upload__tip{
     position: absolute;
     bottom: 20px;
    height: 15px;
    line-height: 15px;
  }
  .write_head li:nth-of-type(2){
    /*background-color: #ffffff;*/
    width: 70%;
    padding-left: 0.5%;
    padding-right: 0.5%;
    position: relative;

  }
  .write_head .el-form{
    width: 100%;
     position: absolute;
     left: 10px;
     bottom: 20px;
     height: 50px;
  }
  .head_select{
    width: 19%;
    float: left;
    position: relative;
    z-index: 10000;
  }
  .head_title{
     width: 100%;
    position: absolute;
    left: -18%;

  }


  .head_title  .el-input{
    width: 323%;
  }
  /*.el-form-item .head_title .el-input{*/
    /*left: 0;*/
    /*width: 100%;*/
  /*}*/


  .write_head li:nth-of-type(3){
    /*background-color: indianred;*/
    width: 10%;
  }
 .head_btn{
     margin-top: 20px;

 }

  .head_btn:nth-of-type(1){
     margin-left: 10%;
  }

  .el-main{
     line-height: 30px;
  }
  .time_line .el-divider{
      margin: 20px 0;
    margin-top: 0;
  }
  .time_line .el-divider__text.is-center{
     border-radius: 10px;
  }
  /*----------markdow 编辑器。----------*/


  /*-----首页上传------*/
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 147px;
    height: 147px;
    line-height: 147px;
    text-align: center;
    border:1px solid #409EFF;
  }
  .avatar {
    width: 178px;
    height: 147px;
    display: block;

  }


  /*---------------------*/



</style>
